#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QMenu *menu_file = menuBar()->addMenu("文件");
    QAction *actOpen = new QAction("打开", this);
    menu_file->addAction(actOpen);

    QAction *actClose = new QAction("关闭", this);
    menu_file->addAction(actClose);

    connect(actOpen, &QAction::triggered, this, &MainWindow::onOpenFile);
    connect(actClose, &QAction::triggered, this, &MainWindow::onCloseFile);

    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(centralWidget);

    view_ = new FormatView(centralWidget);
    view_->setModel(nullptr);
    layout->addWidget(view_);  // 将QTreeView添加到垂直布局中

    centralWidget->setLayout(layout);  // 将垂直布局设置为主窗口的布局

    setCentralWidget(centralWidget);
}

MainWindow::~MainWindow()
{
    if(model_) delete model_;
    delete view_;
}

int MainWindow::onOpenFile(){
    auto f = QFileDialog::getOpenFileName(this, tr("Open File"));
    if (!f.isEmpty()) {
        model_ = new FormatModel(f, this);
        connect(view_, &FormatView::nodeDoubleClicked, model_, &FormatModel::showItem);
        view_->setModel(model_);
    }

    return 0;
}

int MainWindow::onCloseFile()
{
    view_->setModel(nullptr);
    return 0;
}
